<template>


</template>

<script>

export default {
  data () {
    return {
      path: "ws://127.0.0.1:8000/api/v1/ws/chat/",
      socket: "",
			user: ""
    }
  },
  mounted () {
    // this.init()
    // this.test()
  },
  methods: {
    test () {
      console.log('websocket');
    },
    connect (user) {
			this.user = user
      if(typeof(WebSocket) === "undefined"){
        alert("您的浏览器不支持socket")
      }else{
        // 实例化socket
        this.socket = new WebSocket(this.path + user)
        // 监听socket连接
        this.socket.onopen = this.open
        // 监听socket错误信息
        this.socket.onerror = this.error
        // 监听socket消息
        this.socket.onmessage = this.getMessage
      }
    },
    open: function () {
      console.log("socket连接成功")
      this.send("大家好！")
    },
    error: function () {
      console.log("socket连接错误")
    },
    getMessage: function (msg) {
			this.$emit("addMessage", msg.data)
    },
    send: function (params) {
      this.socket.send(params)
    },
    close: function () {
			console.log("socket连接关闭")
    },
    destroyed () {
			// 关闭socket连接
			this.socket.close()
      // 销毁监听
      this.socket.onclose = this.close
    }
  }
}
</script>